<?php
/**
 * Created by PhpStorm.
 * User: Dean.Wu
 * Date: 2018/3/5 0005
 * Time: 19:13
 */
namespace App\Models;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\DB;

class AdminUsers extends Authenticatable
{
    use Notifiable;
    protected $rememberTokenName = '';
    protected $table = 'admin_users';
    protected $fillable = [
        'name', 'password',
    ];


    /**
     * 一个用户有哪些角色
     */
    public function roles()
    {
        return $this->belongsToMany(AdminRole::class, 'admin_role_user', 'user_id', 'role_id')->withPivot(['user_id', 'role_id']);
    }

    /**
     * 是否有某个角色
     */
    public function isInRoles($roles)
    {
        return !! $roles->intersect($this->roles)->count();
    }

    /**
     * 是否有权限
     */
    public function hasPermission($permission)
    {
        return $this->isInRoles($permission->roles);
    }

    /**
     * 给用户分配角色
     */
    public function assignRole($roleName)
    {
        $role = AdminRole::where('name', $roleName)->first();
        return $this->roles()->save($role);
    }

    /**
     * 删除user和role的关联
     */
    public function deleteRole($role)
    {
        return $this->roles()->detach($role);
    }

    public static function getInfoById($id){
        return DB::table('admin_users')->where('id',$id)->first();
    }

}
